/**
* Linkenstein  - Google Chrome extension for adveanced hyperlink copying.
* Copyright (C) 2013  Mykola Bespaliuk
*/

var urlshortener = urlshortener || {};

//noinspection JSUnusedGlobalSymbols
urlshortener.api = {
    name:     "urlshortener",
    version:  "v1",
    key:      "AIzaSyD2cxky6GHkiYL6fZnaw4p-Q3n4kLfMoy4",
    auth: {
        client_id: "834045119170-mif64bnoagnfkee5glhg8u5fqq5pp3ka.apps.googleusercontent.com",
        scope:     "https://www.googleapis.com/auth/urlshortener",
        immediate: true
    }
};
/**
 * Uses the API key from mapping to let know the
 * service which application uses it
 */
urlshortener.setKey = function() {
    //noinspection JSUnresolvedFunction
    gapi.client.setApiKey( urlshortener.api.key );
};
/**
 * Get the short url and pass result to the callback
 * @param url
 * @param callback
 */
urlshortener.insert = function( url, callback ) {
    urlshortener.makeAuthorizedApiCall( urlshortener.insertImplementation, { url: url, callback: callback } );
};
/**
 * Actual request for short url
 * @param parameters
 */
urlshortener.insertImplementation = function( parameters ) {
    //noinspection JSUnresolvedVariable
    var url  = parameters.url,
    callback = parameters.callback,
    //noinspection JSUnresolvedVariable,JSUnusedGlobalSymbols,JSUnresolvedFunction,JSCheckFunctionSignatures
    request = gapi.client.urlshortener.url.insert( {
        resource: { "longUrl": url }
    } );
    urlshortener.insertImplementation.numAttempts = 0;
    //noinspection JSUnresolvedFunction
    request.execute( function( response ) {
        if( response.code == 400 && urlshortener.insertImplementation < 2 ) {
            urlshortener.insertImplementation += 1;
            urlshortener.makePlainApiCall( urlshortener.insertImplementation, parameters );
        } else if ( response.result.id == undefined ) {
            callback( parameters.url )
        } else {
            callback( response.result.id );
        }
    } );
};
/**
 * Making authorized request
 * @param callback
 * @param parameters
 */
urlshortener.makeAuthorizedApiCall = function( callback, parameters ) {

    urlshortener.setKey();
    //noinspection JSUnresolvedVariable,JSUnresolvedFunction
    gapi.auth.authorize( urlshortener.api.auth, function() {
        //noinspection JSUnresolvedVariable
        gapi.client.load( urlshortener.api.name, urlshortener.api.version,
            function() {
                callback( parameters );
            }
        )
    } );
};

urlshortener.makePlainApiCall = function( callback, parameters ) {

    urlshortener.setKey();
    gapi.client.load( urlshortener.api.name, urlshortener.api.version,
        function() {
            callback( parameters );
        }
    );

};